<template>
  <div>
    <h1>发起工资处理</h1>


    <el-table :data="records" border stripe>
      <el-table-column type="index" width="50" />
      <el-table-column v-for="col in columns" :key="col.id" :label="col.label" :width="col.width">
        <template #default="scope">
          <el-input v-if="notEditColumns.some(item => item == col.id)" v-model="scope.row[col.id]" placeholder=""
            size="normal"></el-input>
          <span v-else>
            {{ scope.row[col.id] }}
          </span>
        </template>
      </el-table-column>

    </el-table>
    <el-button @click="saveDataToDatabase" type="primary">发放工资</el-button>

    <el-dialog :destroy-on-close="true" :title="title" v-model="isVisible" width="60%">
      <span></span>
      <template #footer>
        <span>
          <router-view @ref-table="refTable" :data="data"></router-view>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, defineEmits } from 'vue'
import request from '@/api/request.js'
import router from '@/router'

// 判断是否显示弹窗
let isVisible = ref(false)
let title = ref("");

// 弹窗关闭后重新加载数据
let refTable = () => {
  isVisible.value = false
  loadData();
}

// 新增操作
let toInsert = (route) => {
  isVisible.value = true
  router.push("/salary/outsize/insert")
}
let data = ref({})

// 编辑操作
let toUpdate = (row, route) => {
  data.value = row
  isVisible.value = true
  router.push("/salary/outsize/update")
}

// 原编辑保存方法（未修改）
const saveUpdate = () => {
  console.log(records.value)
  // 发起ajax请求，将recoreds发送到服务器，后台@RequestBody List类型接收
}

// 表格数据相关（未修改）
const tableData = ref([])
const records = ref([])
const notEditColumns = ["amountDue","paySalary","otherChargebacks", "issuanceStatus"]
const columns = [
  { id: 'empName', label: '员工姓名' },
  { id: 'departmental', label: '所在部门' },
  { id: 'postsname', label: '岗位' },
  { id: 'amountDue', label: '应发工资' },
  { id: 'paySalary', label: '绩效工资' },
  { id: 'subsidy', label: "补贴" },
  { id: 'socialSecurity', label: '当月缴纳社保' },
  { id: 'accumulationFund', label: '当月缴纳公积金' },
  { id: 'otherChargebacks', label: '当月其他扣款' },
  { id: 'personalIncomeTax', label: '当月应纳税所得额' },
  { id: 'actualAmount', label: '当月实发' },
  { id: 'releaseDate', label: '发放时间' },
  { id: 'createdBy', label: '提交人' },
  { id: 'issuanceStatus', label: '流程状态' }
]

let formData = ref({})
let emits = defineEmits(['ref-table'])

// 时间校验核心逻辑
const getCurrentYearMonth = () => {
  const now = new Date();
  return {
    year: now.getFullYear(),
    month: now.getMonth() + 1
  };
};

const checkHasIssued = async () => {
  const { year, month } = getCurrentYearMonth();
  try {
    const response = await request({
      url: '/outsize/find',
      method: 'get',
      params: { year, month }
    });
    return response.data && response.data.length > 0;
  } catch (error) {
    console.error('校验工资发放状态失败：', error);
    alert('校验失败，请刷新页面重试');
    return true;
  }
};

// 保存数据到数据库
const saveDataToDatabase = async () => {
  const hasIssued = await checkHasIssued();
  if (hasIssued) {
    const { year, month } = getCurrentYearMonth();
    alert(`当前${year}年${month}月工资已发放，不可重复发起！`);
    return;
  }

  if (!records.value || records.value.length === 0) {
    alert('没有可保存的数据');
    return;
  }

  request({
    url: '/outsize/saveBatch',
    method: 'post',
    data: records.value
  }).then(response => {
    if (!response.success) {
      emits('ref-table');
      alert('工资发放成功');
    } else {
      alert(`保存失败：${response.message || '未知错误'}`);
    }
  }).catch(error => {
    console.error('保存数据出错：', error);
    alert('网络错误，保存失败');
  });
};

// 查询个人所得税率
const getPersonalTaxRate = async (taxableIncome) => {
  try {
    if (taxableIncome <= 0) {
      return 0;
    }
    
    const response = await request({
      url: '/salary/setup/rate/app',
      method: 'get',
      params: {
        a: taxableIncome,
        current: 1,
        size: 1
      }
    });
    
    if (response.data && response.data.records && response.data.records.length > 0) {
      return response.data.records[0].rate || 0;
    }
    return 0;
  } catch (error) {
    console.error('查询个人所得税率失败：', error);
    return 0;
  }
};

// 加载员工基础数据（修改部分：处理默认记录）
let loadDatas = () => {
  tableData.value = [];
  return request({
    url: '/salary/setup/empdisposition/list',
    method: 'get',
  }).then(res => {
    const empList = res.data || [];
    const detailRequests = empList.map(empItem => {
      const tableItem = {
        emp: empItem.emp,
        empName: empItem.emp,
        departmental: empItem.departmental,
        postsname: empItem.postsName,
        amountDue: empItem.baseSalary,
        paySalary: empItem.paySalary,
        subsidy: empItem.subsidy,
        socialSecurity: '',
        accumulationFund: '',
        otherChargebacks: '',
        personalIncomeTax: '',
        actualAmount: '',
        releaseDate: '',
        createdBy: '',
        issuanceStatus: ''
      };
      tableData.value.push(tableItem);

      return request({
        url: '/salary/setup/risks/list',
        method: 'get',
        params: {
          emp: empItem.emp,
          ...formData.value
        }
      }).then(async detailRes => {
        // 后端已处理，如果没有该员工记录则返回emp为"默认"的记录
        const securityList = detailRes.data || [];
        // 取第一条记录（无论是员工本人的还是默认的）
        const detailData = securityList.length > 0 ? securityList[0] : {};
        
        const targetItem = tableData.value.find(item => item.emp === empItem.emp);
        
        if (targetItem) {
          // 计算社保总和
          let socialSecuritySum = (detailData.pensionInsuranceIndividual || 0) +
            (detailData.healthInsuranceIndividual || 0) +
            (detailData.unemploymentInsuranceIndividual || 0);
          
          // 计算应纳税所得额
          const taxableIncome = (targetItem.amountDue || 0) + 
                               (targetItem.paySalary || 0) +
                               (targetItem.subsidy || 0) - 
                               socialSecuritySum -
                               (targetItem.otherChargebacks || 0) - 
                               5000;  // 5000元起征点
          
          // 查询对应的税率
          const taxRate = await getPersonalTaxRate(taxableIncome);
          
          // 计算个人所得税
          const personalIncomeTax = taxableIncome * taxRate / 100;
          
          // 赋值计算结果到表格项
          targetItem.socialSecurity = socialSecuritySum;
          targetItem.accumulationFund = detailData.housingProvidentIndividual || 0;
          targetItem.otherChargebacks = 0;
          targetItem.personalIncomeTax = personalIncomeTax > 0 ? personalIncomeTax : 0;
          targetItem.actualAmount = (targetItem.amountDue || 0) + 
                                   (targetItem.paySalary || 0) +
                                   (targetItem.subsidy || 0) - 
                                   socialSecuritySum -
                                   (targetItem.otherChargebacks || 0) - 
                                   targetItem.personalIncomeTax;
          targetItem.issuanceStatus = "未发放";
        }
        return tableData.value;
      });
    });

    return Promise.all(detailRequests).then(finalTableData => {
      records.value = finalTableData[0] || [];
      loadDataset(records.value);
      return records.value;
    });
  }).catch(error => {
    console.error('数据加载失败:', error);
  });
};

// 加载员工姓名
let loadDataset = (tableRecords) => {
  tableRecords.forEach(async (record, index) => {
    try {
      const response = await request({
        url: '/into/getByIds',
        method: 'get',
        params: {
          id: record.emp
        }
      });
      if (response.data && response.data.employeeName) {
        tableRecords[index].empName = response.data.employeeName;
      }
    } catch (error) {
      console.error(`获取员工${record.emp}信息失败:`, error);
    }
  });
}

// 初始加载数据
loadDatas();

// 加载历史发放记录
let loadData = () => {
  request({
    url: '/outsize/find',
    method: 'get',
    params: {
      ...formData.value
    }
  }).then(res => {
    records.value = res.data || [];
    console.log('从后端获取的列表数据：', records.value);
  }).catch(error => {
    console.error('查询列表数据失败:', error);
    alert('查询失败，请重试');
  });
};
</script>

<style scoped></style>
